package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 56. 合并区间
 * 剑指 Offer II 074. 合并区间
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/27 13:58
 */
public class Merge {

    public int[][] merge(int[][] intervals) {
        int length = intervals.length;
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int[][] item = new int[length][2];
        item[0][0] = intervals[0][0];
        item[0][1] = intervals[0][1];
        int index = 0;
        for (int i = 1; i < length; i++) {
            int a = intervals[i][0];
            int b = intervals[i][1];
            if (a > item[index][1]) {
                index++;
                item[index][0] = a;
                item[index][1] = b;
            } else {
                item[index][1] = Math.max(b, item[index][1]);
            }
        }
        return Arrays.copyOf(item, index + 1);
    }

}
